package com.hzzftech.watchdog.busi.service.impl;

import com.hzzftech.watchdog.busi.core.executor.starter.KettleEnvironmentStarter;
import com.hzzftech.watchdog.busi.domain.RJob;
import com.hzzftech.watchdog.busi.mapper.RJobMapper;
import com.hzzftech.watchdog.busi.service.IRJobService;
import com.hzzftech.watchdog.common.core.text.Convert;
import com.hzzftech.watchdog.common.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 数据库资源库_jobService业务层处理
 * 
 * @author kt-watchdog
 * @date 2022-01-27
 */
@Service
public class RJobServiceImpl implements IRJobService 
{
    @Autowired
    private RJobMapper rJobMapper;

    public static Logger logger = LoggerFactory.getLogger(RJobServiceImpl.class);

    /**
     * 查询数据库资源库_job
     * 
     * @param idJob 数据库资源库_job主键
     * @return 数据库资源库_job
     */
    @Override
    public RJob selectRJobByIdJob(Long idJob)
    {
        return rJobMapper.selectRJobByIdJob(idJob);
    }

    /**
     * 查询列表总数
     * @param rJob
     * @return
     */
    @Override
    public Integer selectRJobTotal(RJob rJob) {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        try {
            String sql = "select count(*) from r_job";
            if (StringUtils.isNotEmpty(rJob.getNAME())) {
                sql += " where `NAME` like '%" + rJob.getNAME() + "%'";
            }
            Result result = repository.getDatabase().execStatement(sql);
            List<RowMetaAndData> rows = result.getRows();
            if (CollectionUtils.isNotEmpty(rows)) {
                return rows.get(0).getInteger(0).intValue();
            }
        } catch (Exception e) {
            logger.error("查询JOB列表信息失败", e);
            throw new RuntimeException("查询JOB列表信息失败",e);
        }
        return null;
    }

    /**
     * 查询数据库资源库_job列表
     * 
     * @param rJob 数据库资源库_job
     * @return 数据库资源库_job
     */
    @Override
    public List<RJob> selectRJobList(RJob rJob, Integer pgNum, Integer pgSize, String orderBy)
    {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        try {
            String sql = "select count(*) from r_job";
            if (StringUtils.isNotEmpty(rJob.getNAME())) {
                sql += " where `NAME` like '%" + rJob.getNAME()+"%'";
            }
            sql += " limit " + (pgNum - 1) * pgSize +"," + pgSize;
            if (StringUtils.isNotEmpty(orderBy)) {
                sql += orderBy; // " order by MODIFIED_DATE desc"
            }
            Result result = repository.getDatabase().execStatement(sql);
            List<RowMetaAndData> rows = result.getRows();
            if (CollectionUtils.isNotEmpty(rows)) {
                List<RJob> jobList = new ArrayList<>(20);
                for (RowMetaAndData rowMetaAndData : rows) {
                    Long idJob = rowMetaAndData.getInteger(0);
                    Long idDirectory = rowMetaAndData.getInteger(1) ;
                    String name = rowMetaAndData.getString(2, "");
                    String description = rowMetaAndData.getString(3, "");
                    String extendedDescription = rowMetaAndData.getString(4, "");
                    String jobVersion = rowMetaAndData.getString(5, "");
                    Long jobStatus = rowMetaAndData.getInteger(6);
                    Long idDatabaseLog = rowMetaAndData.getInteger(7);
                    String tableNameLog = rowMetaAndData.getString(8, "");
                    String createdUser = rowMetaAndData.getString(9, "");
                    Date createdDate = rowMetaAndData.getDate(10, null);
                    String modifiedUser = rowMetaAndData.getString(11, "");
                    Date modifiedDate = rowMetaAndData.getDate(12, null);
                    Integer userBatchId = rowMetaAndData.getInteger(13) == null ? null : rowMetaAndData.getInteger(13).intValue();
                    Integer passBatchId = rowMetaAndData.getInteger(14) == null ? null : rowMetaAndData.getInteger(14).intValue();
                    Integer useLogField = rowMetaAndData.getInteger(15) == null ? null : rowMetaAndData.getInteger(15).intValue();
                    String sharedFIle = rowMetaAndData.getString(16, "");
                    RJob j = new RJob();
                    j.setIdJob(idJob);
                    j.setIdDirectory(idDirectory);
                    j.setNAME(name);
                    j.setDESCRIPTION(description);
                    j.setExtendedDescription(extendedDescription);
                    j.setJobVersion(jobVersion);
                    j.setJobStatus(jobStatus);
                    j.setIdDatabaseLog(idDatabaseLog);
                    j.setTableNameLog(tableNameLog);
                    j.setCreatedUser(createdUser);
                    j.setCreatedDate(createdDate);
                    j.setModifiedDate(modifiedDate);
                    j.setModifiedUser(modifiedUser);
                    j.setUseBatchId(userBatchId);
                    j.setPassBatchId(passBatchId);
                    j.setUseLogfield(useLogField);
                    j.setSharedFile(sharedFIle);
                    j.setDirectoryPath(repository.findDirectory(new LongObjectId(idJob)).getPath());
                    jobList.add(j);
                }
                return jobList;
            }
        } catch (Exception e) {
            logger.error("查询JOB列表信息失败", e);
            throw new RuntimeException("查询JOB列表信息失败",e);
        }
        return new ArrayList<>(0);

    }

    /**
     * 新增数据库资源库_job
     * 
     * @param rJob 数据库资源库_job
     * @return 结果
     */
    @Override
    public int insertRJob(RJob rJob)
    {
        return rJobMapper.insertRJob(rJob);
    }

    /**
     * 修改数据库资源库_job
     * 
     * @param rJob 数据库资源库_job
     * @return 结果
     */
    @Override
    public int updateRJob(RJob rJob)
    {
        return rJobMapper.updateRJob(rJob);
    }

    /**
     * 批量删除数据库资源库_job
     * 
     * @param idJobs 需要删除的数据库资源库_job主键
     * @return 结果
     */
    @Override
    public int deleteRJobByIdJobs(String idJobs)
    {
        return rJobMapper.deleteRJobByIdJobs(Convert.toStrArray(idJobs));
    }

    /**
     * 删除数据库资源库_job信息
     * 
     * @param idJob 数据库资源库_job主键
     * @return 结果
     */
    @Override
    public int deleteRJobByIdJob(Long idJob)
    {
        return rJobMapper.deleteRJobByIdJob(idJob);
    }
}
